<template>
  <!-- 二次封装element form组件 -->
  <div>
    <el-form
      ref="ruleForm"
      :model="dataList"
      :label-position="labelPosition"
      :rules="rules"
    >
      <div v-for="v of formData" :key="v.prop">
        <!-- 表单组件 -->
        <el-form-item
          v-if="!['upload'].includes(v.type)"
          :ref="v.prop"
          :class="v.prop"
          :label="v.label"
          :prop="v.prop"
        >
          <template
            #label
            v-if="['applicableScenario', 'unsuitableScenario'].includes(v.prop)"
          >
            <div class="drawerFormLabel">
              {{ v.label }} ({{
                dataList[v.prop + "Images"]
                  ? dataList[v.prop + "Images"].length
                  : 0
              }}/6)
              <span
                style="
                  font-size: 12px;
                  font-family: PingFangSC-Regular, PingFang SC;
                  font-weight: 400;
                  color: #909399;
                "
                >支持上传jpg、png格式图片，单张图片大小不超过2M</span
              >
            </div>
          </template>
          <!-- 输入框组件/文本域组件 -->
          <el-input
            :maxlength="v.maxlength ? v.maxlength : ''"
            :show-word-limit="v.maxlength ? true : ''"
            :rows="v.rows"
            v-model.trim="dataList[v.prop]"
            :type="v.type"
            :placeholder="v.placeholder"
          ></el-input>
        </el-form-item>
        <!-- 上传组件 -->
        <div v-if="['upload'].includes(v.type)" class="upload-img">
          <!--  如下代码必须保留，否则上传删除有bug 后续查找原因-->

          <el-upload
            :ref="v.prop"
            style="margin-bottom: 22px; position: relative"
            :action="getFullPath('file/upload')"
            list-type="picture-card"
            :file-list="dataList[v.showProp] ? dataList[v.showProp] : []"
            :headers="{ Authorization: $cookies.get('access_token_ygd') }"
            :data="{ fileType: 'img', isPublic: 1 }"
            :before-upload="
              (file, fileList) => {
                return beforeUpload(file);
              }
            "
            accept="image/jpeg,image/png"
            :limit="6"
            :on-success="
              (response, file, fileList) => {
                return handleAvatarSuccess(response, file, fileList, v);
              }
            "
            :on-error="handleAvatarError"
            :on-change="
              (file, fileList) => {
                return handlerChange(file, fileList, v);
              }
            "
          >
            <!-- <i slot="default" class="el-icon-plus"><span>点击上传</span></i> -->
            <!-- <el-button size="small" icon="el-icon-plus" type="text"
              >点击上传</el-button
            > -->
            <span slot="default" class="noDataUpload">
              <i class="el-icon-plus"></i>
              <div>点击上传</div>
            </span>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                style="object-fit: contain"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-view"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file, v)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog
            :modal="false"
            title="预览图片"
            top="8vh"
            :visible.sync="dialogVisible"
          >
            <img
              width="100%"
              style="
                max-height: 80vh;
                object-fit: contain;
                disaply: block;
                line-height: 0;
              "
              :src="dialogImageUrl"
              alt=""
            />
          </el-dialog>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import configs from "@/configs";
export default {
  name: "FormEl",
  props: {
    // 表单渲染数据
    formData: {
      type: Array,
      default() {
        return [];
      },
    },
    // 表单数据
    dataInfo: {
      type: Object,
      default() {
        return {};
      },
    },
    // 表单校验规则
    rules: {
      type: Object,
      default() {
        return {};
      },
    },
    // label-position
    labelPosition: {
      type: String,
      default() {
        return "top";
      },
    },
  },
  computed: {},
  data() {
    return {
      dialogImageUrl: "", //图片放大
      dialogVisible: false, //显示放大的图片
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
        // {
        //   name: "food2.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
      dataList: JSON.parse(JSON.stringify(this.dataInfo)),
    };
  },
  watch: {
    dataInfo(newVal) {
      this.dataList = newVal;
      console.log("this.dataList", this.dataList);
    },
  },

  created() {
    this.showImg();
  },
  methods: {
    handlerChange(file, fileList, obj) {
      const el = this.$refs[obj.prop][0].$children[1].$el;

      if (fileList.length == 6) {
        el.style.display = "none";
        el.style.position = "absolute";
        el.style.right = "15px";
      }
    },
    // 处理图片回显
    showImg() {
      // return function (data, keys) {
      this.formData.forEach((v) => {
        if (v.type == "upload") {
          let arr = this.dataList[v.prop] ? this.dataList[v.prop] : [];
          let newArr = [];
          arr.forEach((v) => {
            newArr.push({
              name: "name",
              url: configs.STATIC_URL + "/" + v,
            });
            // }
          });
          // showProp绑定的字段来回显数据
          this.dataList[v.showProp] = newArr;
          this.$nextTick(() => {
            // 超出6张隐藏上传控件
            // console.log('超出6张隐藏上传控件',this.dataList [v.prop]);
            if (this.dataList[v.prop] && this.dataList[v.prop].length >= 6) {
              const el = this.$refs[v.prop][0].$children[1].$el;
              el.style.display = "none";
            }
          });
        }
      });
    },

    // 图片上传失败
    handleAvatarError(err) {
      console.log("err--图片上传失败", err);
      this.$message.error(JSON.parse(err.message).msg);
    },

    // 图片格式限制
    beforeUpload(file) {
      const isJPGorPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log("isJPGorPNG", isJPGorPNG);
      if (!isJPGorPNG) {
        this.$message.error("请上传格式为jpg、png的图片");
      }
      if (!isLt2M) {
        this.$message.error("请上传大小不超过2M的图片");
      }
      return isJPGorPNG && isLt2M;
    },
    // 图片上传成功
    handleAvatarSuccess(response, file, fileList, obj) {
      console.log("图片上传...", this.dataList[obj.showProp]);
      if (response.code == 200) {
        this.dataList[obj.prop] ? "" : (this.dataList[obj.prop] = []); //后台返回null 处理成数组格式
        this.dataList[obj.prop].push(response.data.filename);
        // const arr = [];
        // this.dataList [obj.prop].forEach((v) => {
        //   // if (v instanceof Object) {
        //   //   arr.push(v.imagePath);
        //   // } else {
        //   //   arr.push(v);
        //   // }
        //   arr.push(v);
        // });
        // this.dataList [obj.prop] = arr;

        var random = Math.random().toFixed(13);
        var randomNumber = random * Math.pow(10, 13);

        console.log("fixedNumber", random, randomNumber);

        this.dataList[obj.showProp].push({
          name: "name",
          url: configs.STATIC_URL + "/" + response.data.filename,
          uid: randomNumber,
        });
        console.log("图片上传成功", this.dataList[obj.showProp]);
        // 超出6张隐藏上传控件
        if (this.dataList[obj.prop].length >= 6) {
          const el = this.$refs[obj.prop][0].$children[1].$el;
          el.style.display = "none";
        }
      } else {
        this.$message.error(response.msg);
      }
    },
    // 图片移除
    handleRemove(file, obj) {
      const el = this.$refs[obj.prop][0];

      const { showProp, prop } = obj;
      const ishowProp = this.dataList[showProp].findIndex((item) => {
        let b = file.response
          ? !item.url.includes(file.response.data.filename)
          : item.url !== file.url;
        return !b;
      });
      //  this.dataList [prop] = JSON.parse(JSON.stringify(this.dataList [prop]));
      this.dataList[showProp].splice(ishowProp, 1);
      const iProp = this.dataList[prop].findIndex((item) => {
        let b = file.response
          ? !item.includes(file.response.data.filename)
          : !file.url.includes(item);
        return !b;
      });
      // this.dataList [prop] = JSON.parse(JSON.stringify(this.dataList [prop]));
      this.dataList[prop].splice(iProp, 1);
      el.uploadFiles.splice(iProp, 1);
      // const { showProp, prop } = obj;
      // this.dataList [showProp] = this.dataList [showProp].filter((item) => {
      //   console.log("0000", file, item);
      //   let b = file.response
      //     ? !item.url.includes(file.response.data.filename)
      //     : item.url !== file.url;
      //   console.log("判断0", b);
      //   return b;
      // });

      // this.dataList [prop] = this.dataList [prop].filter((item) => {
      //   console.log("1111", file, item, !file.url.includes(item));
      //   let b = file.response
      //     ? !item.includes(file.response.data.filename)
      //     : !file.url.includes(item);

      //   console.log("判断1", b);

      //   return b;
      // });
      if (this.dataList[obj.prop].length < 6) {
        const el = this.$refs[obj.prop][0].$children[1].$el;
        el.style.display = "inline-block";
      }
      if (this.dataList[obj.prop].length <= 4) {
        console.log(1111, el.$children[1].$el);
        const ell = el.$children[1].$el;
        ell.style.position = "";
        ell.style.right = "";
      }
      console.log("ii", this.dataList[obj.prop].length);
    },
    // 图片放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //校验表单-提交按钮 外部调用方法
    $submitForm(cb) {
      console.log("校验表单-提交按钮", this.$refs.ruleForm);
      // return
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log("校验通过");
          cb && cb(true, JSON.parse(JSON.stringify(this.dataList)));
        } else {
          console.log("校验失败");
          cb && cb(false, JSON.parse(JSON.stringify(this.dataList)));
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-form-item__label {
    color: #303133 !important;
  }
  .noDataUpload {
    font-size: 12px;
    .el-icon-plus {
      margin-top: 14px;
    }
    &:hover {
      color: #0170ef;

      .el-icon-plus {
        color: #0170ef;
        margin-top: 14px;
      }
    }
  }
  .el-dialog__wrapper {
    z-index: 2006 !important;
  }
  .el-upload {
    position: relative;
    // .el-button {
    //   display: flex;
    //   flex-wrap: wrap;
    //   align-items: center;
    //   position: absolute;
    //   left: 0;
    //   top: 0;
    //   right: 0;
    //   bottom: 0;
    //   margin: auto;
    //   height: 70%;
    //   .el-icon-plus {
    //     width: 100%;
    //   }
    //   span {
    //     font-size: 13px;
    //     width: 100%;
    //     display: inline-block;
    //   }
    // }
  }
  .upload-img {
    .el-dialog__wrapper {
      height: 100%;
      overflow-y: hidden;
    }

    .el-dialog__body {
      padding-top: 5px !important;
      margin-bottom: 10px;
    }
  }
  .el-dialog__header {
    padding: 20px;
    padding-bottom: 10px;
  }
  .el-dialog__title {
    line-height: 24px;
    font-size: 18px;
    color: #303133;
  }
  .el-upload-list__item{
    transition:all 0s cubic-bezier(0.55, 0, 0.1, 1) !important;
  }
  .el-upload-list__item,
  .el-upload--picture-card {
    width: 80px !important;
    height: 80px !important;
    border: 1px solid #c0ccda;
    background: #f7f8fb;
    border: 1px dashed #dfe5ee;
    border-style: dashed !important;
    line-height: 22px;
    color: #909399;
    // padding-top: 10px;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    margin: 0 8px 8px 0;
    display: inline-block;
  }
  .el-upload--picture-card:hover {
    border-color: #0170ef;
  }
  .el-upload-list__item-thumbnail {
    width: 80px;
    height: 80px;
  }
}
</style>
